package models

import (
	"card/dao"
	"context"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

const TableNameMemberTeamLevel = "member_team_level"

// MemberTeamLevel mapped from table <member_team_level>
type MemberTeamLevel struct {
	ID     int64 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
	UserID int64 `gorm:"column:user_id;not null;comment:用户id" json:"user_id"` // 用户id
	Pid    int64 `gorm:"column:pid;not null;comment:推荐人id" json:"pid"`        // 推荐人id
	Level  int   `gorm:"column:level;not null;comment:层级" json:"level"`       // 层级
	ctx    context.Context
	db     *gorm.DB
}

// TableName MemberTeamLevel's table name
func (*MemberTeamLevel) TableName() string {
	return TableNameMemberTeamLevel
}

func NewMemberLevel(c context.Context) *MemberTeamLevel {
	if ctx, ok := c.(*gin.Context); ok {
		c = ctx.Request.Context()
	}
	return &MemberTeamLevel{
		ctx: c,
		db:  new(dao.Card).GetDb(),
	}
}

func (m *MemberTeamLevel) GetOne(opts ...dao.DbOption) (info MemberTeamLevel, err error) {
	tx := m.db.WithContext(m.ctx).Model(&MemberTeamLevel{})
	for _, option := range opts {
		option(tx)
	}
	err = tx.Limit(1).Find(&info).Error
	return
}

func (m *MemberTeamLevel) InsertAll(arr []MemberTeamLevel) (int64, error) {
	tx := m.db.WithContext(m.ctx).Model(&MemberTeamLevel{})
	res := tx.Create(arr)
	if res.Error != nil {
		return 0, res.Error
	}
	return res.RowsAffected, nil
}
